package com.junxonline.instant.admin.service.config.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junxonline.instant.common.util.common.RedisUtils;
import com.junxonline.instant.dao.entity.model.config.Dict;
import com.junxonline.instant.dao.entity.model.config.DictGroup;
import com.junxonline.instant.dao.entity.vo.config.DictGroupVO;
import com.junxonline.instant.dao.mapper.config.DictGroupMapper;
import com.junxonline.instant.dao.mapper.config.DictMapper;
import com.junxonline.instant.admin.service.config.DictGroupService;
import com.junxonline.instant.common.constant.RedisConstant;
import com.junxonline.instant.common.entity.common.CommonReqPage;
import com.junxonline.instant.common.entity.common.CommonRespPage;
import com.junxonline.instant.common.enumeration.AdminErrorEnum;
import com.junxonline.instant.common.exception.AdminBizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 数据字典分组接口实现类
 *
 * @author JunX
 * @date 2021-07-18
 */
@Service
@Transactional
public class DictGroupServiceImpl extends ServiceImpl<DictGroupMapper, DictGroup> implements DictGroupService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private DictGroupMapper dictGroupMapper;

    @Autowired
    private DictMapper dictMapper;

    /**
     * 查询数据字典分组列表
     *
     * @param vo 请求参数
     * @return CommonRespPage<DictGroup>
     */
    @Override
    public CommonRespPage<DictGroup> queryList(CommonReqPage<DictGroupVO> vo) {
        LambdaQueryWrapper<DictGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getName()), DictGroup::getName, vo.getQueryParams().getName());
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getCode()), DictGroup::getCode, vo.getQueryParams().getCode());
        return CommonRespPage.success(dictGroupMapper.selectPage(new Page<>(vo.getPage(), vo.getPageSize()), wrapper));
    }

    /**
     * 查询数据分组字典
     *
     * @param id DictGroup
     * @return Dict
     */
    @Override
    public DictGroup query(Long id) {
        DictGroup dictGroup = dictGroupMapper.selectById(id);
        Assert.notNull(dictGroup, AdminErrorEnum.DATA_IS_NOT_EXISTS.getMsg());
        return dictGroup;
    }

    /**
     * 新增数据分组字典
     *
     * @param dictGroup 请求参数
     */
    @Override
    public void add(DictGroup dictGroup) {
        int count = dictGroupMapper.selectCount(new LambdaQueryWrapper<DictGroup>().eq(DictGroup::getCode, dictGroup.getCode()));
        if (count > 0) {
            throw new AdminBizException(AdminErrorEnum.DATA_IS_EXISTS);
        }
        dictGroupMapper.insert(dictGroup);
    }

    /**
     * 编辑数据字典分组
     *
     * @param dictGroup 请求参数
     */
    @Override
    public void edit(DictGroup dictGroup) {
        DictGroup model = dictGroupMapper.selectById(dictGroup.getId());
        int count = dictGroupMapper.selectCount(new LambdaQueryWrapper<DictGroup>()
                .ne(DictGroup::getId, dictGroup.getId())
                .eq(DictGroup::getCode, dictGroup.getCode()));
        if (count > 0) {
            if (!dictGroup.getId().equals(model.getId())) {
                throw new AdminBizException(AdminErrorEnum.DATA_IS_EXISTS);
            }
        }
        String oldCode = model.getCode();
        dictGroupMapper.updateById(dictGroup);
        // 删除缓存中的数据
        if (redisUtils.hasKey(RedisConstant.KEY_DICT + oldCode)) {
            redisUtils.del(RedisConstant.KEY_DICT + oldCode);
        }
        // 查询该分组下所有的数据字典数据
        List<Dict> dictList = dictMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, dictGroup.getId()));
        if (dictList.size() > 0) {
            // 将该分组的数据字典集合存入缓存中
            redisUtils.set(RedisConstant.KEY_DICT + dictGroup.getCode(), JSON.toJSONString(dictList));
        }
    }

    /**
     * 删除数据字典分组
     *
     * @param ids 请求参数
     */
    @Override
    public void delete(List<Long> ids) {
        List<DictGroup> dictGroupList = dictGroupMapper.selectBatchIds(ids);
        for (DictGroup dictGroup : dictGroupList) {
            // 清理缓存中的数据
            redisUtils.del(RedisConstant.KEY_DICT + dictGroup.getCode());
            // 删除该分组下所有的数据字典
            dictMapper.delete(new LambdaUpdateWrapper<Dict>().eq(Dict::getParentId, dictGroup.getId()));
            // 删除数据库中的数据
            dictGroupMapper.deleteById(dictGroup.getId());
        }
    }

}
